<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Jina Reader</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/marked/4.0.2/marked.min.js"></script>
    <style>
        body {
            font-family: Helvetica, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
            box-sizing: border-box;
        }
        h1 {
            font-size: 24px;
            margin-bottom: 16px;
        }
        h1 + p {
            margin-bottom: 20px;
            color: #666;
        }
        #url-form {
            display: flex;
            flex-direction: column;
            gap: 12px;
        }
        #url-input, #format-select, #submit-btn, #markdown-raw, .copy-btn, #prompt-textarea, #run-prompt-btn {
            font-size: 16px;
            padding: 10px 12px;
            box-sizing: border-box;
            border-radius: 6px;
        }
        #url-input, #format-select {
            width: 100%;
            border: 1px solid #ccc;
            background: #fff;
        }
        #url-input:focus, #format-select:focus, #prompt-textarea:focus {
            outline: none;
            border-color: #4CAF50;
            box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
        }
        #submit-btn, .copy-btn, #run-prompt-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
            font-weight: 500;
        }
        #submit-btn:hover, .copy-btn:hover, #run-prompt-btn:hover {
            background-color: #45a049;
        }
        #submit-btn:active, .copy-btn:active, #run-prompt-btn:active {
            transform: scale(0.98);
        }
        #markdown-raw, #prompt-textarea {
            width: 100%;
            height: 200px;
            margin-top: 20px;
            resize: vertical;
            border: 1px solid #ccc;
        }
        #prompt-textarea {
            height: 100px;
            margin-top: 0;
        }
        #markdown-rendered {
            margin-top: 20px;
            border: 1px solid #ccc;
            padding: 10px;
            overflow-wrap: break-word;
            border-radius: 6px;
        }
        #loading, #prompt-loading {
            display: none;
            margin-top: 20px;
            color: #666;
        }
        #result, #prompt-result {
            display: none;
            line-height: 1.5;
            font-size: 16px;
        }
        #prompt-rendered {
            font-family: system-ui, -apple-system, sans-serif;
            max-width: 65ch;
            margin: 1.5em 0;
        }
        #prompt-rendered p {
            margin: 1em 0;
            line-height: 1.6;
        }
        #prompt-rendered ul {
            margin: 1em 0;
            padding-left: 2em;
        }
        #prompt-rendered li {
            margin: 0.5em 0;
            line-height: 1.4;
        }
        iframe {
            width: 100%;
            height: 500px;
            box-sizing: border-box;
            border: 1px solid #ccc;
            border-radius: 6px;
        }
        @media (min-width: 540px) {
            #url-form {
                flex-direction: row;
                flex-wrap: wrap;
                align-items: center;
            }
            #url-input {
                flex: 1;
                min-width: 200px;
            }
            #format-select {
                width: auto;
                min-width: 140px;
            }
            #submit-btn {
                width: auto;
            }
        }
    </style>
</head>
<body>
    <h1>Jina Reader</h1>
    <p>An interface for the <a href="https://jina.ai/reader/">Jina Reader API</a>.</p>
    <form id="url-form">
        <input type="text" id="url-input" placeholder="Enter URL" required>
        <select id="format-select">
            <option value="markdown">Markdown</option>
            <option value="html">HTML</option>
            <option value="text">Text</option>
            <option value="llm_markdown">LLM Markdown</option>
        </select>
        <button type="submit" id="submit-btn">Submit</button>
    </form>
    <div id="loading">Loading...</div>
    <div id="result">
        <textarea id="markdown-raw" readonly></textarea>
        <button id="copy-btn" class="copy-btn">Copy to clipboard</button>
        <iframe id="markdown-rendered" sandbox></iframe>
    </div>

    <div id="prompt-section" style="margin-top: 2em; padding-top: 2em; border-top: 1px solid #eee; display: none;">
        <h2>Run a prompt with Claude</h2>
        <textarea id="prompt-textarea">Respond in markdown. You summarize the pasted in text. Start with a overall summary in a single paragraph. Then show a bullet pointed list of the most interesting illustrative quotes from the piece. Then a bullet point list of the most unusual ideas. Finally provide a longer summary that covers points not included already</textarea>
        <button id="run-prompt-btn">Run prompt</button>
        <div id="prompt-loading" style="margin: 1em 0; font-style: italic;">Generating...</div>
        <div id="prompt-result">
            <div id="prompt-rendered"></div>
            <button id="prompt-copy-btn" class="copy-btn" style="margin-top: 1em;">Copy to clipboard</button>
        </div>
    </div>

    <script>
        const urlForm = document.getElementById('url-form');
        const urlInput = document.getElementById('url-input');
        const formatSelect = document.getElementById('format-select');
        const loading = document.getElementById('loading');
        const result = document.getElementById('result');
        const markdownRaw = document.getElementById('markdown-raw');
        const copyBtn = document.getElementById('copy-btn');
        const markdownRendered = document.getElementById('markdown-rendered');

        // Claude elements
        const promptTextarea = document.getElementById('prompt-textarea');
        const runPromptBtn = document.getElementById('run-prompt-btn');
        const promptLoading = document.getElementById('prompt-loading');
        const promptResult = document.getElementById('prompt-result');
        const promptRendered = document.getElementById('prompt-rendered');
        const promptCopyBtn = document.getElementById('prompt-copy-btn');

        urlForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const url = urlInput.value;
            const format = formatSelect.value;
            if (!url) return;

            loading.style.display = 'block';
            result.style.display = 'none';

            try {
                let fetchOptions = {
                    method: 'GET'
                };

                if (format !== 'llm_markdown') {
                    fetchOptions.headers = {
                        "X-Return-Format": format
                    };
                }

                const response = await fetch(`https://r.jina.ai/${url}`, fetchOptions);
                const content = await response.text();
                markdownRaw.value = content;

                let htmlContent;
                if (format === 'html') {
                    htmlContent = content;
                } else {
                    htmlContent = `
                        <html>
                            <head>
                                <style>
                                    body { font-family: Helvetica, sans-serif; line-height: 1.6; color: #333; }
                                    img { max-width: 100%; height: auto; }
                                </style>
                            </head>
                            <body>
                                ${format === 'text' ? `<pre>${content}</pre>` : marked.parse(content)}
                            </body>
                        </html>
                    `;
                }
                markdownRendered.srcdoc = htmlContent;
                result.style.display = 'block';
                document.getElementById('prompt-section').style.display = 'block';
            } catch (error) {
                console.error('Error fetching content:', error);
                markdownRaw.value = 'Error fetching content. Please try again.';
                markdownRendered.srcdoc = '<p>Error fetching content. Please try again.</p>';
                result.style.display = 'block';
                document.getElementById('prompt-section').style.display = 'none';
            } finally {
                loading.style.display = 'none';
            }
        });

        copyBtn.addEventListener('click', () => {
            markdownRaw.select();
            document.execCommand('copy');
            
            const originalText = copyBtn.textContent;
            copyBtn.textContent = 'Copied';
            
            setTimeout(() => {
                copyBtn.textContent = originalText;
            }, 1500);
        });

        // Get the API key from localStorage or prompt the user to enter it
        function getApiKey() {
            let apiKey = localStorage.getItem("ANTHROPIC_API_KEY");
            if (!apiKey) {
                apiKey = prompt("Please enter your Anthropic API key:");
                if (apiKey) {
                    localStorage.setItem("ANTHROPIC_API_KEY", apiKey);
                }
            }
            return apiKey;
        }

        // Handle Claude prompt
        runPromptBtn.addEventListener('click', async () => {
            const apiKey = getApiKey();
            if (!apiKey) {
                alert("API key not found. Please enter your Anthropic API key.");
                return;
            }

            // Get the prompt and content
            const systemPrompt = promptTextarea.value;
            const content = markdownRaw.value;

            if (!content) {
                alert("No content to analyze. Please fetch a URL first.");
                return;
            }

            promptLoading.style.display = 'block';
            promptResult.style.display = 'none';

            try {
                const response = await fetch("https://api.anthropic.com/v1/messages", {
                    method: "POST",
                    headers: {
                        "x-api-key": apiKey,
                        "anthropic-version": "2023-06-01",
                        "content-type": "application/json",
                        "anthropic-dangerous-direct-browser-access": "true"
                    },
                    body: JSON.stringify({
                        model: "claude-3-5-haiku-latest",
                        max_tokens: 4096,
                        system: systemPrompt,
                        messages: [
                            {
                                role: "user",
                                content: content
                            }
                        ]
                    })
                });

                const data = await response.json();
                console.log(JSON.stringify(data, null, 2));
                const markdown = data.content[0].text;
                
                promptRendered.innerHTML = marked.parse(markdown);
                promptResult.style.display = 'block';

                let responseMarkdown = markdown;
                promptRendered.innerHTML = marked.parse(responseMarkdown);

                promptCopyBtn.onclick = () => {
                    navigator.clipboard.writeText(responseMarkdown);
                    const originalText = promptCopyBtn.textContent;
                    promptCopyBtn.textContent = 'Copied';
                    setTimeout(() => {
                        promptCopyBtn.textContent = originalText;
                    }, 1500);
                };

            } catch (error) {
                console.error("Error calling Claude API:", error);
                promptRendered.innerHTML = '<p class="error">Error generating summary. Please try again.</p>';
            } finally {
                promptLoading.style.display = 'none';
            }
        });
    </script>
</body>
</html>
